import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  // InputNumber,
  DatePicker,
  // Modal,
  // message,
  Divider,
  Table,
} from 'antd';
// import StandardTable from '@/components/StandardTable';
import DictSelect from '@/components/DictSelect';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { getAuthorityToken } from '@/utils/authority';

import styles from '../List/TableList.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ batchFileimportTask, dictionary, loading }) => ({
  batchFileimportTask,
  dictionary,
  loading: loading.models.batchFileimportTask,
}))
@Form.create()
class BatchFileimportTaskList extends PureComponent {
  state = {
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const {
      dispatch,
      batchFileimportTask: {
        data: {
          pagination: { pageSize },
        },
      },
    } = this.props;
    dispatch({
      type: 'batchFileimportTask/fetch',
      payload: {
        size: pageSize,
      },
    });

    dispatch({
      type: 'dictionary/loadDict',
      codetype: 'job.process.state',
    });
    dispatch({
      type: 'dictionary/loadDict',
      codetype: 'job.process.way',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      page: pagination.current - 1,
      size: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'batchFileimportTask/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'batchFileimportTask/fetch',
      payload: {},
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  doSearch = () => {
    const {
      dispatch,
      form,
      exampleOrder: {
        data: {
          pagination: { pageSize },
        },
      },
    } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        size: pageSize,
        ...fieldsValue,
        // le_createDate: fieldsValue.le_createDate && fieldsValue.le_createDate.format('YYYY-MM-DD HH:mm:ss'),
        // ge_createDate: fieldsValue.ge_createDate && fieldsValue.ge_createDate.format('YYYY-MM-DD HH:mm:ss'),
        createDate: null,
        ge_createDate:
          fieldsValue.createDate && fieldsValue.createDate[0].format('YYYY-MM-DD HH:mm:ss'),
        le_createDate:
          fieldsValue.createDate && fieldsValue.createDate[1].format('YYYY-MM-DD HH:mm:ss'),
      };

      // console.log(values)

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'batchFileimportTask/fetch',
        payload: values,
      });
    });
  };

  handleSearch = e => {
    e.preventDefault();

    this.doSearch();
  };

  handleExport = e => {
    e.preventDefault();
    const { form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const fvalues = {
        ...fieldsValue,
        le_createDate:
          fieldsValue.le_createDate && fieldsValue.le_createDate.format('YYYY-MM-DD HH:mm:ss'),
        ge_createDate:
          fieldsValue.ge_createDate && fieldsValue.ge_createDate.format('YYYY-MM-DD HH:mm:ss'),
      };

      let params = '';
      //      for (const v in fvalues) {
      //        if (fvalues[v] !== null && fvalues[v] !== undefined) {
      //          params += `${v}=${fvalues[v]}&`;
      //        }
      //      }
      Object.entries(fvalues).forEach(item => {
        const key = item[0];
        const value = item[1];
        if (value !== null && value !== undefined) {
          params += `${key}=${value}&`;
        }
      });

      open(`/api/admin/batch/batchFileimportTask/export?${params}tokenid=${getAuthorityToken()}`);
    });
  };

  handleShow = (e, key) => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push(`/batch/batchFileimportTask/${key}`));
  };

  handleDownloadError = (e, key) => {
    window.open(
      `/api/admin/batch/batchFileimportTask/downloadErrorFile?taskId=${key}&tokenid=${getAuthorityToken()}`
    );
  };

  renderAdvancedForm() {
    const { dictionary, form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="任务名称">
              {getFieldDecorator('like_taskName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="任务类型">
              {getFieldDecorator('eq_taskType')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="处理状态">
              {getFieldDecorator('eq_procState')(
                <DictSelect
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  dictList={dictionary['job.process.state']}
                />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="处理方式">
              {getFieldDecorator('eq_procWay')(
                <DictSelect
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  dictList={dictionary['job.process.way']}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <FormItem label="提交时间">
              {getFieldDecorator('createDate')(
                <RangePicker
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                />
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button icon="search" type="primary" htmlType="submit">
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
                {/* <Button icon="export" style={{ marginLeft: 8 }} onClick={this.handleExport}>
              导出
            </Button> */}
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  render() {
    const {
      batchFileimportTask: { data },
      loading,
    } = this.props;
    const { selectedRows } = this.state;
    const { list, pagination } = data;

    const columns = [
      // {
      //   title: '任务ID',
      //   dataIndex: 'taskId',
      // },
      {
        title: '提交时间',
        dataIndex: 'createDate',
      },
      {
        title: '任务名称',
        dataIndex: 'taskName',
      },
      {
        title: '任务类型',
        dataIndex: 'taskType',
      },
      // {
      //   title: '操作类型',
      //   dataIndex: 'operType',
      // },
      // {
      //   title: '操作人账号',
      //   dataIndex: 'operator',
      // },
      // {
      //   title: '操作人ID',
      //   dataIndex: 'operatorId',
      // },
      // {
      //   title: '操作人名称',
      //   dataIndex: 'operatorName',
      // },
      // {
      //   title: '业务对象',
      //   dataIndex: 'bsBo',
      // },
      {
        title: '总数',
        dataIndex: 'totalRec',
      },
      {
        title: '成功数',
        dataIndex: 'succRec',
      },
      {
        title: '失败数',
        dataIndex: 'failRec',
      },
      // {
      //   title: '失败日志',
      //   dataIndex: 'failLog',
      // },
      {
        title: '处理状态',
        dataIndex: 'procStateName',
      },
      // {
      //   title: '处理方式',
      //   dataIndex: 'procWayName',
      // },

      // {
      //   title: '处理服务器IP',
      //   dataIndex: 'serverIp',
      // },
      {
        title: '开始执行时间',
        dataIndex: 'beginTime',
      },
      {
        title: '完成执行时间',
        dataIndex: 'finishTime',
      },
      {
        title: '消耗时间（秒）',
        dataIndex: 'costTime',
      },
      // {
      //   title: '处理文件',
      //   dataIndex: 'proceFileName',
      // },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={e => this.handleShow(e, record.taskId)}>查看</a>
            <Divider type="vertical" />
            <a onClick={e => this.handleDownloadError(e, record.taskId)}>下载失败日志</a>
          </Fragment>
        ),
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
    };

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>{selectedRows.length > 0 && <span />}</div>
            {/* <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              // onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey="taskId"
            /> */}

            <Table
              loading={loading}
              rowKey="taskId"
              dataSource={list}
              columns={columns}
              pagination={paginationProps}
              onChange={this.handleStandardTableChange}
              bordered
              scroll={{ x: 1800 }}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
export default BatchFileimportTaskList;
